package org.lds.scheduled.job.admin.starter.holder;

import org.lds.scheduled.job.common.model.db.PageResult;
import org.lds.scheduled.job.common.model.dto.ResultDTO;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.util.List;
import java.util.Objects;

public abstract class AbstractGetValidInstanceStarter<T> implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        searchAll();
    }

    private void searchAll() {
        search(0L);
    }

    private void search(Long id) {
        ResultDTO<PageResult<T>> resultDTO = pageInstances(id);
        if (!ResultDTO.isSuccess(resultDTO) || Objects.isNull(resultDTO.getData())) return;

        List<T> instances = resultDTO.getData().getData();
        for (T instance : instances) {
            save(instance);
        }

        int size = instances.size();
        if (size == 500) {
            id = id(instances.get(size - 1));
            search(id);
        }
    }

    protected abstract void save(T instance);

    protected abstract Long id(T instance);

    protected abstract ResultDTO<PageResult<T>> pageInstances(Long id);
}
